<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\tool\Result;
use think\exception\ValidateException;
use app\common\model\Address as AddressModel;
use think\Response;

class Address extends Base
{
    public function index(): Response
    {
        $map = ['uid' => $this->user->id];
        $list = AddressModel::getList($map, false, 'id', ['p', 'c', 'd'],
            'id,uid,nickname,tel,province,city,district,details,default');
        foreach ($list as &$item) {
            $p = $item->p ? $item->p->title : '';
            $c = $item->c ? $item->c->title : '';
            $d = $item->d ? $item->d->title : '';
            $item->address = $p . $c . $d;
            unset($item->p, $item->c, $item->d);
        }

        return Result::success('success', $list);
    }

    public function info($id): Response
    {
        $info = AddressModel::withoutField('create_time,update_time,delete_time')
            ->where(['id' => $id, 'uid' => $this->user->id])->find();
        if (!$info) return Result::fail('地址不存在或已删除');
        $p = $info->p ? $info->p->title : '';
        $c = $info->c ? $info->c->title : '';
        $d = $info->d ? $info->d->title : '';
        $info->address = $p . $c . $d;
        unset($info->p);
        unset($info->c);
        unset($info->d);

        return Result::success('success', $info);
    }

    public function save(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Address');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(AddressModel::add($param, $this->user));
    }

    public function setDefault(): Response
    {
        return Result::fastReturn(AddressModel::setDefault($this->request->post('id'), $this->user));
    }

    public function delete(): Response
    {
        return Result::fastReturn(AddressModel::edit($this->request->post('id'), $this->user));
    }
}